﻿using JNPF.Basics.Logic;
using JNPF.Basics.Logic.Common.Login;
using JNPF.Basics.Models.DataInterface;
using JNPF.Basics.Models.DataInterface.Dtos;
using JNPF.Basics.Models.DataInterface.Entities;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 数据接口
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2020.09.01 
    /// </summary>
    [Route("api/[controller]")]
    public class DataInterfaceController : BaseApiController
    {
        private DataInterfaceBll dataInterfaceBll = new DataInterfaceBll();
        private UserBll userBll = new UserBll();
        private DictionaryDataBll dictionaryDataBll = new Logic.DictionaryDataBll();

        #region Get
        /// <summary>
        /// 获取接口列表(分页)
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] DataInterfaceListQuery input)
        {
            var pageInput = input.MapTo<PageInput>();
            pageInput.queryJson = JsonHelper.ToJson(new { input.categoryId });
            var data = await dataInterfaceBll.GetList(pageInput);
            var outList = new List<DataInterfaceListOutput>();
            data.list.ForEach(x =>
                outList.Add(new DataInterfaceListOutput()
                {
                    id = x.Id,
                    categoryId = x.CategoryId,
                    creatorTime = x.CreatorTime,
                    creatorUser = userBll.GetUserName(x.CreatorUserId),
                    dataType = x.DataType,
                    dbLinkId = x.DBLinkId,
                    description = x.Description,
                    enCode = x.EnCode,
                    enabledMark = x.EnabledMark,
                    fullName = x.FullName,
                    path = x.Path,
                    query = x.Query,
                    requestMethod = x.RequestMethod,
                    requestParameters = x.RequestParameters,
                    responseType = x.ResponseType,
                    sortCode = x.SortCode
                })
            );
            var output = new PageResult()
            {
                list = outList,
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 获取接口列表下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector")]
        public async Task<ResponseResult> GetSelector()
        {
            List<DataInterfaceSelectorOutput> tree = new List<DataInterfaceSelectorOutput>();
            var data = await dataInterfaceBll.GetSelector();
            foreach (var entity in data)
            {
                var dictionaryDataEntity = await dictionaryDataBll.GetInfo(entity.CategoryId);
                if (dictionaryDataEntity != null && tree.Where(t => t.id == entity.CategoryId).Count() == 0)
                {
                    DataInterfaceSelectorOutput firstModel = dictionaryDataEntity.MapTo<DataInterfaceSelectorOutput>();
                    firstModel.categoryId = "0";
                    firstModel.children = new List<DataInterfaceTreeModel>();
                    DataInterfaceTreeModel treeModel = entity.MapTo<DataInterfaceTreeModel>();
                    treeModel.categoryId = "1";
                    treeModel.parentId = dictionaryDataEntity.Id;
                    firstModel.children.Add(treeModel);
                    tree.Add(firstModel);
                }
                else
                {
                    DataInterfaceTreeModel treeModel = entity.MapTo<DataInterfaceTreeModel>();
                    treeModel.categoryId = "1";
                    treeModel.parentId = entity.CategoryId;
                    var parent = tree.Where(t => t.id == entity.CategoryId).FirstOrDefault();
                    if (parent != null)
                    {
                        parent.children.Add(treeModel);
                    }
                }
            }
            return Success(tree);
        }

        /// <summary>
        /// 获取接口数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = (await dataInterfaceBll.GetInfo(id)).MapTo<DataInterfaceInfoOutput>();
            return Success(data);
        }

        /// <summary>
        /// 访问接口
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}/Actions/Response")]
        public async Task<ResponseResult> ActionsResponse(string id)
        {
            var data = await dataInterfaceBll.GetInfo(id);
            if (1.Equals(data.DataType))
            {
                var dt = await dataInterfaceBll.GetData(id, data.Query);
                return Success(dt);
            }
            else if (2.Equals(data.DataType))
            {
                return Success(data.Query.ToObject());
            }
            else
            {
                var isPost = data.RequestMethod.ToLower().Equals("post");
                var output = WebHelper.HttpWebRequest(data.Path, data.RequestParameters, Encoding.UTF8, isPost);
                return Success(output);
            }
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加接口
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] DataInterfaceCrInput input)
        {
            var entity = input.MapTo<DataInterfaceEntity>();
            var isOk = await dataInterfaceBll.Create(entity);
            return isOk > 0 ? Success("创建成功") : Error("创建失败");
        }

        /// <summary>
        /// 修改接口
        /// </summary>
        /// <param name="id">主键id</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] DataInterfaceUpInput input)
        {
            var entity = input.MapTo<DataInterfaceEntity>();
            var isOk = await dataInterfaceBll.Update(id, entity);
            return isOk > 0 ? Success("修改成功") : Error("修改失败");
        }

        /// <summary>
        /// 删除接口
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await dataInterfaceBll.GetInfo(id);
            var isOk = await dataInterfaceBll.Delete(entity);
            return isOk > 0 ? Success("删除成功") : Error("删除失败");
        }

        /// <summary>
        /// 更新接口状态
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/State")]
        public async Task<ResponseResult> UpdateState(string id)
        {
            var entity = await dataInterfaceBll.GetInfo(id);
            entity.EnabledMark = entity.EnabledMark == 1 ? 0 : 1;
            var isOk = await dataInterfaceBll.Update(id, entity);
            return isOk > 0 ? Success("修改成功") : Error("修改失败");
        }
        #endregion
    }
}
